package com.isatechindonesia.isatracker.service;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.isatechindonesia.isatracker.DBClass;
import com.isatechindonesia.isatracker.Logger;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;

public class GPSSendData extends Service{
	
	private static Timer timer = new Timer();	

	@Override
	public void onCreate() {
		super.onCreate();
		Log.i("create--->", "Timer task created");				

	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		timer.cancel();
		timer = null;
		Log.i("destroy--->", "Timer task destroyed");

	}

	@Override
	public void onStart(Intent intent, int startid) {
		super.onStart(intent, startid);
		int updateInterval = 120;
		
		timer = new Timer("UpdateTimer");
		timer.schedule(updateTask, 1000, updateInterval * 1000);

		Log.i("start--->", "Timer task started " + updateInterval);

	}
	
	private TimerTask updateTask = new TimerTask() {		
		@Override
		public void run() {			
			
			DBClass db = new DBClass(getApplicationContext());
			List<Logger> logList = db.getLog();
			boolean connected;
			
			SharedPreferences pref = getApplicationContext().getSharedPreferences("gpsconfig", MODE_PRIVATE);			
			String idgps = pref.getString("idgps", "0000");
			String address = "";
			
			for (Logger cn : logList) {
				try {

					InetAddress serverAddr = InetAddress.getByName("202.149.91.13");
					Log.d("client--->", "C: Connecting...");
					Socket socket = new Socket(serverAddr, 1500);
					connected = true;
					if (connected) {
						try {
							Log.d("client--->", "C: Sending command.");
							PrintWriter out = new PrintWriter(
									new BufferedWriter(new OutputStreamWriter(
											socket.getOutputStream())), true);
							// WHERE YOU ISSUE THE COMMANDS
							out.println(idgps+"," + cn.getLat() + "," + cn.getLon() + "," + cn.getSpeed()
									+ "," + address + "," + cn.getHeading() + "," + cn.getAltitude()
									+ "," + cn.getAccuracy() + "," + cn.getDate());
							Log.d("client--->", "C: Sent.");
							db.deleteLog(cn.get_id());
						} catch (Exception e) {
							Log.e("client--->", "S: Error", e);
						}
					}
					socket.close();
					Log.d("client--->", "C: Closed.");
				} catch (Exception e) {
					Log.e("client--->", "C: Error", e);
					connected = false;
				}
			}
			
			Log.i("timer--->", "Timer task doing work");
		}
	};
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

}
